﻿package ua.mihaylenko.cardsplugin.utils 
{
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	import flash.events.NetStatusEvent;
	import flash.utils.Dictionary;
	public class LocalStorage 
	{
		private var _so:SharedObject;
		private var _dict:Dictionary;
		
		public function LocalStorage():void
		{
			_so = SharedObject.getLocal("ecard-plugin");
			if (_so.data["contents"])
			{
				_dict = _so.data["contents"];
			}
			else
			{
				_dict = new Dictionary(true);
			}
		}
		
		public function saveValue(key:String, value:String):void
		{
			_dict[key] = value;
			_so.data["contents"] = _dict;
            
            var flushStatus:String = null;
            try {
                flushStatus = _so.flush(10000);
            } catch (error:Error) {
                trace("Error...Could not write SharedObject to disk\n");
            }
            if (flushStatus != null) {
                switch (flushStatus) {
                    case SharedObjectFlushStatus.PENDING:
                        trace("Requesting permission to save object...\n");
                        _so.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
                        break;
                    case SharedObjectFlushStatus.FLUSHED:
                        trace("Value flushed to disk.\n");
                        break;
                }
            }
		}
		
		public function getValue(key:String):String
		{
			if (_dict[key])
			{
				return _dict[key];
			}
			return "";
		}
		
		private function onFlushStatus(event:NetStatusEvent):void
		{
            trace("User closed permission dialog...\n");
            switch (event.info.code) {
                case "SharedObject.Flush.Success":
                    trace("User granted permission -- value saved.\n");
                    break;
                case "SharedObject.Flush.Failed":
                    trace("User denied permission -- value not saved.\n");
                    break;
            }
            _so.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
        }

	}	
}